import { createApp, h } from 'vue'
import { ElIcon, ElTooltip } from 'element-plus'
import { QuestionFilled } from '@element-plus/icons-vue'

function render(target: any, tip: string) {
  const app = createApp({
    render: () => h(
      ElTooltip,
      {
        content: tip,
        placement: 'top',
        effect: 'dark',
        enterable: false,
        popperClass: 'form-item-tip-popper',
        showAfter: 100,
        hideAfter: 0,
      },
      {
        default: () => h(ElIcon, {}, () => [h(QuestionFilled)]),
      },
    ),
  })

  const div = document.createElement('div')
  div.classList.add('form-item-tip-icon')
  app.mount(div)

  // 查找是否已经存在
  const exist = target.querySelector('.form-item-tip-icon')
  exist && target.removeChild(exist)
  target.appendChild(div)
}

export default {
  beforeUpdate(el: HTMLElement, bind: any) {
    const {value} = bind
    if (!value) return

    requestIdleCallback(() => {
      const target = el.querySelector('[class~="el-form-item__label"]')
      if (target) {
        render(target, value)
      } else {
        Array.from(el.children).forEach((item, index) => {
          const target = item.querySelector('.el-form-item__label')
          target && render(target, value)
        })
      }
    })
  },
}

